package com.ea.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ea.admin.mapper.CompanyInfoMapper;
import com.ea.admin.pojo.Enum.RoleCode;
import com.ea.admin.pojo.po.AdminAccount;
import com.ea.admin.pojo.po.CompanyInfo;
import com.ea.admin.pojo.vo.account.ContactAdminVo;
import com.ea.admin.pojo.vo.company.CompanyVo;
import com.ea.admin.service.AccountService;
import com.ea.admin.service.CompanyPermissionService;
import com.ea.admin.service.CompanyService;
import com.ea.admin.service.ConfigService;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class CompanyServiceImpl implements CompanyService {
    @Resource
    CompanyInfoMapper companyInfoMapper;
    @Resource
    CheckAccountService checkAccountService;
    @Resource
    AccountService accountService;
    @Resource
    CompanyPermissionService companyPermissionService;
    @Resource
    ConfigService configService;


    @Override
    public Long addCompany(Long accountId, Long supCompanyId, String companyName, Long companyContactAccountId, String companyContactName, String companyContactPhoneNum, String companyContactUsername, String companyContactPassword, String companyContactRePassword) {

        // 检查单位名称是否重复
        LambdaQueryWrapper<CompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyInfoLambdaQueryWrapper.eq(CompanyInfo::getCompanyName, companyName)
                .eq(CompanyInfo::getIsDel, 0);
        if (companyInfoMapper.selectCount(companyInfoLambdaQueryWrapper) > 0) {
            throw new BizException(ErrorCode.SYSTEM_RESOURCE_EXISTS_COMPANY_NAME_ERROR);
        }

        // 检查进行操作的管理员是否有足够的权限
        companyPermissionService.checkCompanyPermission(accountId, supCompanyId);

        CompanyInfo companyInfo = new CompanyInfo();
        CompanyInfo supCompanyInfo = null;
        companyInfo.setCompanyName(companyName);
        companyInfo.setSupCompanyId(supCompanyId);

        AdminAccount adminAccount;
        // 如果 参数中有id，且其余都为空，则选择现有联系人
        if (
                companyContactAccountId != null
                        && (companyContactUsername == null || companyContactUsername.isEmpty())
                        && (companyContactName == null || companyContactName.isEmpty())
                        && (companyContactPassword == null || companyContactPassword.isEmpty())
                        && (companyContactRePassword == null || companyContactRePassword.isEmpty())
                        && (companyContactPhoneNum == null || companyContactPhoneNum.isEmpty())
        ) {
            // 检查是否是可选的联系人
            adminAccount = checkAccountService.checkAdminAccount(companyContactAccountId);
            // 检查单位联系人是否有足够的权限 —— 或许直接给他添加权限就行了
            // companyPermissionService.checkCompanyPermissionError(supCompanyId, companyContactAccountId);
            // 是否是单位超管
            if (!adminAccount.getAdminRoleId().equals(RoleCode.COMPANY_SUPER_ADMIN.getCode().longValue())) {
                throw new BizException(ErrorCode.USER_PARAM_ERROR_NOT_COMPANY_SUPER_ADMIN);
            }
            companyInfo.setContactAdminId(adminAccount.getAccountId());
        }
        // 如果 参数中有 创建用户相关的参数
        else if (
                (companyContactAccountId == null || companyContactAccountId.equals(0L))
                        && companyContactUsername != null && !companyContactUsername.isEmpty()
                        && companyContactName != null && !companyContactName.isEmpty()
                        && companyContactPassword != null && !companyContactPassword.isEmpty()
                        && companyContactRePassword != null && !companyContactRePassword.isEmpty()
                        && companyContactPhoneNum != null && !companyContactPhoneNum.isEmpty()) {
            // 添加单位联系人 - 单位默认超级管理员
            adminAccount = accountService.addAdmin(
                    companyContactUsername,
                    companyContactPassword,
                    companyContactRePassword,
                    companyContactName,
                    companyContactPhoneNum,
                    RoleCode.COMPANY_SUPER_ADMIN.getCode().longValue());
            companyInfo.setContactAdminId(adminAccount.getAccountId());
        }  else if( (companyContactAccountId == null || companyContactAccountId.equals(0L))
                && (companyContactUsername == null || companyContactUsername.isEmpty())
                && (companyContactName == null || companyContactName.isEmpty())
                && (companyContactPassword == null || companyContactPassword.isEmpty())
                && (companyContactRePassword == null || companyContactRePassword.isEmpty())
                && (companyContactPhoneNum == null || companyContactPhoneNum.isEmpty())){
            // 没有单位联系人，跳过操作
            adminAccount=null;
        }else {
            throw new BizException(ErrorCode.USER_PARAM_ERROR_EITHER_NEW_CONTACT_OR_EXIST_CONTACT);
        }

        // 如果没有上级单位，则层级为0
        if (supCompanyId == null) {
            companyInfo.setLevel(0);
        } else {
            //否则，先获取父级单位的层级，然后加1
            supCompanyInfo = companyInfoMapper.selectById(supCompanyId);
            if (supCompanyInfo == null) {
                throw new BizException(ErrorCode.SYSTEM_RESOURCE_SUP_COMPANY_NOT_EXISTS);
            }
            companyInfo.setLevel(supCompanyInfo.getLevel() + 1);
        }

        companyInfoMapper.insert(companyInfo);

        // 为单位联系人添加该单位的单位权限
        if(!(adminAccount==null)) {
            companyPermissionService.addCompanyPermission(adminAccount.getAccountId(), companyInfo.getCompanyId());
        }

        // 添加单位的默认配置
        // addCompanyConfByDefaultConf(companyInfo.getCompanyId());
        // 为超级管理员和上级单位的管理员添加该单位的权限
        addCompanyPermissionToSuperAdmin(companyInfo.getCompanyId(), supCompanyInfo);

        return companyInfo.getCompanyId();
    }

    private void addCompanyPermissionToSuperAdmin(Long companyId, CompanyInfo supCompanyInfo) {
        // 获得超级管理员的id
        Set<Long> adminIdSet = new HashSet<>(accountService.getSuperAdminIdList());


        // 如果有上级单位，则需要给上级单位的管理员也 添加该单位的管理权限
        if (supCompanyInfo != null) {
            adminIdSet.addAll(companyPermissionService.getAdminId(supCompanyInfo.getCompanyId()));
        }

        // 给超级管理员和上级管理员添加 该单位的管理权限
        companyPermissionService.addCompanyPermission(new ArrayList<>(adminIdSet), companyId);
    }

    @Override
    public List<CompanyVo> getCompanyPermissionById(Long accountId) {
        return companyPermissionService.getCompanyPermission(accountId);
    }

    @Override
    public List<ContactAdminVo> searchContact(Long accountId, Long companyId, String contactName) {
        // 检查当前管理员是否有此单位的权限
        companyPermissionService.checkCompanyPermission(accountId, companyId);

        return companyPermissionService.getAllAdminInfoByCompanyIdAndName(companyId, contactName);
    }

    @Override
    public Integer getCompanyCountByIdList(List<Long> companyIdList) {
        Long count = companyInfoMapper.selectCount(new LambdaQueryWrapper<CompanyInfo>().in(CompanyInfo::getCompanyId, companyIdList));
        return count.intValue();
    }

    @Override
    public void editCompany(Long accountId, Long companyId, String companyName, Long supCompanyId, Long companyContactId) {

        // 检查进行操作的管理员是否有足够的权限
        companyPermissionService.checkAccountCompany(accountId, companyId);

        // 查询单位信息
        CompanyInfo companyInfo = companyInfoMapper.selectById(companyId);

        // 检查单位联系人是否修改
        if (companyContactId!=null && (!companyInfo.getContactAdminId().equals(companyContactId))) {
            AdminAccount adminAccount = checkAccountService.checkAdminAccount(companyContactId);

            // 检查单位联系人是否有足够的权限
            companyPermissionService.checkAccountCompany(companyContactId, companyId);

            // 判断联系人是否是单位超管
            if (!adminAccount.getAdminRoleId().equals(RoleCode.COMPANY_SUPER_ADMIN.getCode().longValue())) {
                throw new BizException(ErrorCode.USER_PARAM_ERROR_NOT_COMPANY_SUPER_ADMIN);
            }

            // 修改单位联系人信息
            companyInfo.setContactAdminId(adminAccount.getAccountId());
        }
        // 修改单位信息
        if (!companyName.equals(companyInfo.getCompanyName())) {

            // 检查单位名称是否重复
            LambdaQueryWrapper<CompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            companyInfoLambdaQueryWrapper.eq(CompanyInfo::getCompanyName, companyName)
                    .eq(CompanyInfo::getIsDel, 0);
            if (companyInfoMapper.selectCount(companyInfoLambdaQueryWrapper) > 0) {
                throw new BizException(ErrorCode.SYSTEM_RESOURCE_EXISTS_COMPANY_NAME_ERROR);
            }

            companyInfo.setCompanyName(companyName);
        }
        if (supCompanyId == null || !supCompanyId.equals(companyInfo.getSupCompanyId())) {
            // 检查上级单位是否存在
            CompanyInfo supCompanyInfo = null;
            if (companyId.equals(supCompanyId)) {
                throw new BizException(ErrorCode.USER_PARAM_ERROR_SUP_COMPANY_ERROR);
            }
            if (supCompanyId != null) {
                supCompanyInfo = companyInfoMapper.selectById(supCompanyId);
                if (supCompanyInfo == null) {
                    throw new BizException(ErrorCode.SYSTEM_RESOURCE_SUP_COMPANY_NOT_EXISTS);
                }
            }
            if (supCompanyInfo != null) {
                companyInfo.setLevel(supCompanyInfo.getLevel() + 1);
            }

            companyInfo.setSupCompanyId(supCompanyId);
        }

        // 更新数据库
        companyInfoMapper.updateById(companyInfo);
    }


    @Override
    public void deleteCompany(Long accountId, Long companyId) {
        // 检查进行操作的管理员是否有足够的权限
        companyPermissionService.checkAccountCompany(accountId, companyId);

        // 获取本单位及其下级单位的id
        List<Long> companyIdList = new ArrayList<>();
        companyIdList.add(companyId);
        List<Long> allRelatedCompanyIdList = companyInfoMapper.getAllSubCompanyIdByCompanyId(companyIdList);

        // 检查下级单位是否含有人员，如果有，则不能删除
        if (companyInfoMapper.checkIfCompanyHasUser(allRelatedCompanyIdList)) {
            throw new BizException(ErrorCode.SYSTEM_RESOURCE_EXISTS_COMPANY_HAS_USER_ERROR);
        }

        // 缉拿查下级单位是否有管理员，如果有，则不能删除
        //if (companyInfoMapper.checkIfCompanyHasAdmin(allRelatedCompanyIdList)) {
        //    throw new BizException(ErrorCode.SYSTEM_RESOURCE_EXISTS_COMPANY_HAS_ADMIN_ERROR);
        //}

        companyInfoMapper.deleteRelatedCompanyByCompanyId(companyIdList);
    }

}
